package com.jt.config;
/*
定义配置类，设计流控网关的返回值:即自定义网关的的响应结果
 */
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
@Configuration
public class Gateway {
    public Gateway(){ //无参构造
        GatewayCallbackManager.setBlockHandler(
                new BlockRequestHandler() {  //匿名内部接口;阻塞请求处理器
                    @Override
                    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                        HashMap<Object, Object> map = new HashMap();
                        map.put("state", 429);//自定义状态码
                        map.put("message", "this is my response");
                        //方式一Gson
                        Gson gson = new Gson();
                        String jsonStr = gson.toJson(map);
                        //方式二
                        //String jsonStr2 = JSON.toJSONString(map);

                       //ok方法仅8版本支持
                        return ServerResponse.ok().body(Mono.just(jsonStr), String.class);
                    }
                }
        );
    }
}
